package com.eonmind.vip.service.impl;

import com.eonmind.common.provider.entity.vip.Subscription;
import com.eonmind.common.provider.entity.vip.VipPackage;
import com.eonmind.user.contract.dto.UserInfoData;
import com.eonmind.vip.dto.UserWelfareDto;
import com.eonmind.vip.mapper.SubscriptionMapper;
import com.eonmind.vip.mapper.VipPackageMapper;
import com.eonmind.vip.service.VipPackageService;
import com.eonmind.vip.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class VipPackageServiceImpl implements VipPackageService {

    @Autowired
    private VipPackageMapper vipPackageMapper;

    @Autowired
    private SubscriptionMapper subscriptionMapper;

    @Override
    public List<VipPackage> getAllPackages() {
        return vipPackageMapper.list();
    }

    @Override
    public List<UserWelfareDto.UserActivePackage> getAllActivePackages(UserInfoData userInfoData) {
        Long userId = userInfoData.getId();
        List<Subscription> actives = subscriptionMapper.findAllActiveSubsByUserId("active", userId);
        ArrayList<UserWelfareDto.UserActivePackage> list = new ArrayList<>();

        for (Subscription sub: actives) {
            VipPackage vipPackage = vipPackageMapper.one(vipPackageMapper.createMgoQuery().eq(VipPackage::getId, sub.getPlanId()));
            UserWelfareDto.UserActivePackage userActivePackage = new UserWelfareDto.UserActivePackage()
                    .setEndTime(TimeUtil.LongToString(sub.getEndDate()))
                    .setStartTime(TimeUtil.LongToString(sub.getEndDate()))
                    .setVipPackage(vipPackage)
                    .setSubscription(sub);
            list.add(userActivePackage);
        }
        return list;
    }
}
